<template>
	<view class="content">
		<!-- 地图容器 -->
		<view id="mapContainer" class="map-container"></view>

		<!-- 操作面板 -->
		<view class="control-panel">
			<view class="draw-group">
				<button class="btn" @click="startDrawing">{{ !isDrawing ? '开始绘制' : '右键结束' }}</button>
				<button class="btn" @click="clearAll">清空所有</button>
				<button class="btn" @click="configArea" :disabled="polygonPoints.length < 3">确定范围</button>
			</view>
		</view>
	</view>
</template>

<script>
const db = uniCloud.databaseForJQL();
const _ = db.command;
const linlier = uniCloud.importObject('linlier');
import getGridCode from '../../utils/getGridCode';
import { gcj02towgs84, wgs84togcj02 } from 'coordtransform';
import { isPointInPolygon, getPolygon } from '@/utils/polygonInMap.js';
export default {
	data() {
		return {
			groups: [],
			linlier: {},
			markers: [],
			center: null,
			map: null,
			mouseTool: null,
			polygon: null,
			polygonPoints: [],
			group: {},
			isDrawing: false,
			clickCoordinates: {}
		};
	},
	mounted() {},
	async onLoad(res) {
		if (res?.data) {
			const formated = JSON.parse(decodeURIComponent(res.data));
			this.linlier = formated;
		}
		this.initMap();
	},
	methods: {
		async getgroups(id) {
			try {
				const res = await db
					.collection('Group')
					.where({
						_id: id
					})
					.get();
				console.log('多边型取到了几个？', res.data);
				return res.data[0];
			} catch (e) {
				console.error('群多边型读取失败', e);
			}
		},
		setCenter() {
			console.log(',,,,,,,', this.clickCoordinates);
			this.center = this.clickCoordinates;
			var makercenter = new AMap.Marker({
				position: [this.center.lng, this.center.lat],
				icon: ''
			});
			this.map.add(makercenter);
		},
		// 初始化地图
		initMap() {
			const key = '90253c298848b952c2810dcdcfd95f49'; // 替换为实际key
			const script = document.createElement('script');
			script.src = `https://webapi.amap.com/maps?v=2.0&key=${key}&plugin=AMap.MouseTool`;
			script.onload = () => {
				this.setupMap();
			};
			document.head.appendChild(script);
		},

		// 地图配置
		setupMap() {
			const [longitude, latitude] = this.linlier.location.coordinates;
			this.map = new AMap.Map('mapContainer', {
				zoom: 12,
				center: [longitude || 119.222214, latitude || 26.046152] // 初始中心点
			});

			var marker = new AMap.Marker({
				position: [longitude || 119.222214, latitude || 26.046152],
				icon: ''
			});
			this.map.add(marker);
			this.getNearByLinlier({ longitude, latitude });

			// 初始化绘图工具
			this.mouseTool = new AMap.MouseTool(this.map);
			// if (Object.keys(this.group).length > 0 && this.group.aMapLocation?.length > 0) {
			// 	this.map.add(this.groupAreaView(this.group));
			// }

			// 监听绘制完成事件
			this.mouseTool.on('draw', (event) => {
				if (event.obj.constructor === AMap.Polygon) {
					this.handleDrawComplete(event.obj);
				}
			});
			this.map.on('click', (event) => {
				console.log('点击坐标11:', event);
				const lng = event.lnglat.getLng();
				const lat = event.lnglat.getLat();
				const clickLocation = { lng, lat };
				this.clickCoordinates = clickLocation;

				console.log('点击坐标:', clickLocation);
				// 你可以在这里添加处理点击坐标的其他逻辑
			});
		},

		//附近群组列表

		async handleAllGroup() {
			if (this.groups.length > 0) {
				for (const group of this.groups) {
					this.map.remove(this.groupAreaView(group));
				}
			}
			const result = await db.collection('Group').get();
			console.log(result);
			this.groups = result.data;
			if (result.data.length > 0) {
				for (const group of result.data) {
					if (Object.keys(group).length > 0 && group.aMapLocation?.length > 0) {
						this.map.add(this.groupAreaView(group));
					}
				}
			}
		},
		groupAreaView(group) {
			if (group && Array.isArray(group.aMapLocation) && group.aMapLocation.length > 0) {
				const groupArea = group.aMapLocation.map((item) => {
					//return wgs84togcj02(item[0], item[1]);
					return item;
				});
				// 创建多边形覆盖物
				const polygon = new AMap.Polygon({
					path: groupArea,
					strokeColor: '#FF33FF', // 线条颜色
					strokeWeight: 2, // 线条宽度
					fillColor: '#1791fc', // 填充颜色
					fillOpacity: 0.4 // 填充透明度
				});
				return polygon;
				// 将多边形添加到地图上
			}
		},
		// 处理绘制完成
		handleDrawComplete(polygon) {
			// 获取路径坐标
			this.isDrawing = false;
			const path = polygon.getPath().map((point) => [point.lng, point.lat]);
			this.polygonPoints = path;

			// 移除旧多边形
			if (this.polygon) {
				this.map.remove(this.polygon);
			}

			// 保存新多边形
			this.polygon = polygon;

			// 设置多边形样式
			polygon.setOptions({
				fillColor: '#1791fc',
				fillOpacity: 0.4,
				strokeColor: '#1791fc',
				strokeWeight: 2
			});
		},

		// 开始绘制
		startDrawing() {
			this.isDrawing = true;
			this.mouseTool.polygon({
				strokeColor: '#1791fc',
				fillColor: '#1791fc',
				fillOpacity: 0.4
			});
		},

		// 清空所有
		clearAll() {
			this.isDrawing = false;
			this.polygonPoints = [];
			if (this.polygon) {
				this.map.remove(this.polygon);
				this.polygon = null;
			}
			this.mouseTool.close(true);
		},

		// 引入 coordtransform 库
		async getNearByLinlier(location) {
			const res = await linlier.getPolygons(location);
			const polygons = res.data.map((item) => ({ polygon: item.serviceArea.coordinates, point: item.location.coordinates }));

			for (const polygon of polygons) {
				const poly = new AMap.Polygon({
					path: polygon.polygon,
					strokeColor: '#FF33FF', // 线条颜色
					strokeWeight: 2, // 线条宽度
					fillColor: '#1791fc', // 填充颜色
					fillOpacity: 0.4 // 填充透明度
				});
				const point = new AMap.Marker({
					position: polygon.point,
					icon: ''
				});
				this.map.add(point);
				this.map.add(poly);
			}

			console.log('获取附近管家逻辑', res);
			//1获取后将范围显示在地图上
		},
		async configArea() {
			if (this.polygonPoints.length < 3) {
				uni.showToast({ title: '请至少绘制3个点形成多边形', icon: 'error' });
				return;
			}

			// 1. 确保多边形闭合（首尾点坐标一致）
			const firstPoint = this.polygonPoints[0];
			const lastPoint = this.polygonPoints[this.polygonPoints.length - 1];
			const closedPoints =
				JSON.stringify(firstPoint) === JSON.stringify(lastPoint)
					? [...this.polygonPoints] // 已闭合，直接用
					: [...this.polygonPoints, firstPoint]; // 未闭合，添加首点到末尾

			// 2. 构建标准 GeoJSON Polygon 格式（关键！）
			// 格式：{ type: "Polygon", coordinates: [[[lng1, lat1], [lng2, lat2], ..., [lng1, lat1]]] }
			const geoPolygon = {
				type: 'Polygon',
				coordinates: [closedPoints] // 注意：必须是二维数组（外层数组包含一个线性环）
			};

			try {
				// 3. 上传到后端（直接传递 GeoJSON 对象）
				const res = await linlier.editLinlier({
					id: this.linlier._id,
					serviceArea: geoPolygon // 直接传 GeoJSON 格式的多边形
				});

				if (res.code === 0) {
					uni.showToast({ title: '服务范围更新成功' });
					setTimeout(() => uni.navigateBack(), 1500);
				} else {
					uni.showToast({ title: res.message || '更新失败', icon: 'none' });
				}
			} catch (error) {
				console.error('更新服务范围失败：', error);
				uni.showToast({ title: '网络错误，请重试', icon: 'none' });
			}
		}
	}
};
</script>

<style>
.map-container {
	width: 100%;
	height: 100vh;
	margin: 20px 0;
}
.content {
	position: relative;
}
.control-panel {
	position: absolute;
	top: 0;
	left: 0;
	display: flex;
	justify-content: space-around;
	padding: 20px;
	background: #ccc;
}

.btn {
	width: 200rpx;
	margin: 10px;
	padding: 8px 16px;
	background: #1890ff;
	color: white;
	border-radius: 4px;
	font-size: 14px;
}

.coordinates-list {
	margin-top: 15px;
	padding: 10px;
	background: white;
	border-radius: 4px;
	max-height: 200px;
	overflow-y: auto;
}

.coordinates-list text {
	display: block;
	margin: 6px 0;
	color: #666;
	font-size: 12px;
}
.view_btn {
	justify-self: end;
	margin-right: 50rpx;
}
</style>
